package tt.dz.biz.service.financial;

import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import tt.dz.biz.dao.trade.TradeDAOImpl;
import tt.dz.common.BusinessException;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.TranErrorCode;
import tt.dz.common.LogUtil;
import tt.dz.vo.TranInfoVO;

@Service("tradeService")
public class TradeService
{
  @Resource(name="tradeDAO")
  private TradeDAOImpl tradeDAO;
  
  public void trade(TranInfoVO tranInfoVO)
    throws Exception
  {
    try
    {
      if (null == tranInfoVO) {
        return;
      }
      int n = this.tradeDAO.insertTranInfo(tranInfoVO);
      if (n == 0) {
        throw new BusinessException(DzErrorCode.TranErrorCode.SAVE_TRAN_INFO_FAIL.value(), DzErrorCode.TranErrorCode.SAVE_TRAN_INFO_FAIL.getDesc(), DzErrorCode.TranErrorCode.SAVE_TRAN_INFO_FAIL.getDesc());
      }
      if (CollectionUtils.isNotEmpty(tranInfoVO.getTranSubVOList()))
      {
        int[] sub = this.tradeDAO.batchInsertTranSubInfo(tranInfoVO.getTranSubVOList());
        if (sub == null) {
          throw new BusinessException(DzErrorCode.TranErrorCode.SAVE_TRAN_SUB_INFO_FAIL.value(), DzErrorCode.TranErrorCode.SAVE_TRAN_SUB_INFO_FAIL.getDesc(), DzErrorCode.TranErrorCode.SAVE_TRAN_SUB_INFO_FAIL.getDesc());
        }
        for (int i : sub) {
          if (i == 0) {
            throw new BusinessException(DzErrorCode.TranErrorCode.SAVE_TRAN_SUB_INFO_FAIL.value(), DzErrorCode.TranErrorCode.SAVE_TRAN_SUB_INFO_FAIL.getDesc(), DzErrorCode.TranErrorCode.SAVE_TRAN_SUB_INFO_FAIL.getDesc());
          }
        }
      }
    }
    catch (Exception e)
    {
      LogUtil.error("交易异常，参数为：" + tranInfoVO, e);
      throw e;
    }
  }
  
  public List<TranInfoVO> queryTranInfoVOs(TranInfoVO tranInfoVO)
    throws Exception
  {
    try
    {
      return this.tradeDAO.queryTranInfo(tranInfoVO);
    }
    catch (Exception e)
    {
      LogUtil.error("查询交易流水异常：", e);
      throw e;
    }
  }
}
